// const CryptoJS = require("crypto-js");
import crypto,{AES, enc,mode,pad} from 'crypto-js'
import pako,{inflate} from 'pako';
import { atob,Base64 } from 'js-base64';
// import {atob} from './Base64'
export class EncryptionToDecrypt{

    static keyStr = '8e61c760fc65b76a';
    static iv = '55f305bc47281b07"';

     /**
      * 加密
      * @param {string} word 加密内容
      */
    static encryptionCryptoJS(word){
        const key = enc.Utf8.parse(this.keyStr),
        srcs = enc.Utf8.parse(word),
        encrypted = AES.encrypt(srcs, key, {
            iv: enc.Utf8.parse(this.iv),
            mode: mode.CBC,
            padding: pad.Pkcs7
        }),
         hexStr = encrypted.ciphertext.toString().toUpperCase();
        return hexStr.toString()
    }
    /**
     * 解密
     * @param {string} word  解密内容
     */
    static decryptionCryptoJS(word){
        if(typeof word === 'object'){
            return word
        }
        const key = enc.Utf8.parse(this.keyStr),
        encryptedHexStr = enc.Hex.parse(word),
        srcs = enc.Base64.stringify(encryptedHexStr),
        decrypt = AES.decrypt(srcs, key, {
           iv: enc.Utf8.parse(this.iv),
           mode: mode.CBC,
           padding: pad.Pkcs7
       });
         return enc.Utf8.stringify(decrypt).toString();
   }

   /**
    * 解压 Gzip 数据
    * @param {string} b64Data 解压
    */
   static unGzip(b64Data){
    let strData = atob(b64Data),
    charData = strData.split('').map(function (x) { return x.charCodeAt(0); }),
    binData = new Uint8Array(charData),
    data = inflate(binData);
    // strData = String.fromCharCode.apply(null, new  	Uint16Array(data));  
    // return decodeURIComponent(strData)（这里也可以直接return返回忽略下面步骤，但是这么做发现中文解压的时候乱码了，使用二进制转字符串的方法得以解决）
    strData = this.byteToString(data)
    return strData
   }
   /**
    * 解决中文乱码
    * @param {*} arr 
    */
   static byteToString(arr){
    if (typeof arr === 'string') {
        return arr;
    }
    let str = '', _arr = arr;
    for (let i = 0; i < _arr.length; i++) {
        let one = _arr[i].toString(2),
            v = one.match(/^1+?(?=0)/);
        if (v && one.length == 8) {
            let bytesLength = v[0].length;
            let store = _arr[i].toString(2).slice(7 - bytesLength);
            for (let st = 1; st < bytesLength; st++) {
                store += _arr[st + i].toString(2).slice(2);
            }
            str += String.fromCharCode(parseInt(store, 2));
            i += bytesLength - 1;
        } else {
            str += String.fromCharCode(_arr[i]);
        }
    }
    return str;
   }
}

export const getSpecifyTxt=(str, findStr = ".")=>{
    if (!str) return null;
    const partition = str?.lastIndexOf(findStr);
    return {
      name: str.substring(0, partition),
      suffix: str.substring(partition, str.length)
    };
  }

  // 计算签名。
function computeSignature(accessKeySecret, canonicalString) {
    return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
  }

  export const AliyunOSSUpdateData = ({AccessKeyId,AccessKeySecret,SecurityToken})=>{

    const date = new Date();
    date.setHours(date.getHours() + 1);
    const policyText = {
      expiration: date.toISOString(), // 设置policy过期时间。
      conditions: [
        // 限制上传大小。
        ["content-length-range", 0, 1024 * 1024 * 1024],
      ],
    };
    
   const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
   const signature = computeSignature(AccessKeySecret || 'eEBn8XSwPrDwDPkKcLR3SGvuV3aEK8AmLo5jQtcgAvV', policy)
    return {
      OSSAccessKeyId:  AccessKeyId || "STS.NSvst8iy8w1XzWk7RL5BXmYhg",
      signature,
      policy,
      'x-oss-security-token': SecurityToken || "CAIS7AF1q6Ft5B2yfSjIr5DDOM6MhKYZwPOzeHHa01IZOc10gpzDhTz2IHFJfHltBewdsfQ3nmFU7/sYlqx6T55OSBQWnx3rPM0Fnzm6aq/t5uaXj9Vd+rDHdEGXDxnkprywB8zyUNLafNq0dlnAjVUd6LDmdDKkLTfHWN/z/vwBVNkMWRSiZjdrHcpfIhAYyPUXLnzML/2gQHWI6yjydBM05lcn0z0guPThmZHMskrk4QekmrNPlePYOYO5asRgBpB7Xuqu0fZ+Hqi7i38Ns0gXqPst0/wco2ab54zHGTlX51CIKe3S7s2/us3iyxCacRqAAQ/UO+dKkfDbbJTFXefZxj61bPynmgB/Z0XZVpTbp6RvxzGs5aMT57CoLKtUSSZV7zA5pVLDvfl3NcCKZLXOWNBLWl4iHgkIZLsdimFvsbBC8DfBDRrgfOlBVCuoFTKm+4dK85i9IaPDN4uizhTixnkX6zkk0fCkURQ0jTLwHzLsIAA=",
    }
  }


  // 节流
export function throttle(fn, delay = 500) {
    let timer = true;
    return function(args) {
      let that = this;
      let _args = arguments;
      if (!timer) {
        return false;
      }
      timer = false;
      setTimeout(() => {
        fn.apply(that, _args);
        timer = true;
      }, delay);
    };
  }